<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 案例接口
 */
class Design extends Api
{
    protected $noNeedLogin = ['getDesignSearchCondition', 'getDesignList', 'getDesignById'];
    protected $noNeedRight = ['*'];

    public function getDesignList()
    {
        if ($this->request->isPost()) {
            $styleIds = $this->request->post('styleIds', '');
            $layoutIds = $this->request->post('layoutIds', '');
            $spaceIds = $this->request->post('spaceIds', '');
            $pageIndex = $this->request->post('pageIndex', 1);
            $pageSize = $this->request->post('pageSize', 10);
            $keyword = $this->request->post('keyword', '');

            $where = [];
            $lay = [];
            if ($keyword) {
                $where['jd.design_name'] = ['LIKE', '%' . $keyword . '%'];
            }
            if ($layoutIds) {
                $layoutIdList = explode(',', $layoutIds);
                foreach ($layoutIdList as $item) {
                    $lay[] = ['LIKE', '%,' . $item . ',%'];
                }
                $lay[] = 'or';
                $where['jd.layout_ids'] = $lay;
            }
            if ($styleIds) {
                $styleIdList = explode(',', $styleIds);
                foreach ($styleIdList as $item) {
                    $sty[] = ['LIKE', '%,' . $item . ',%'];
                }
                $sty[] = 'or';
                $where['jd.style_ids'] = $sty;
            }
            if ($spaceIds) {
                $spaceIdList = explode(',', $spaceIds);
                foreach ($spaceIdList as $item) {
                    $spa[] = ['LIKE', '%,' . $item . ',%'];
                }
                $spa[] = 'or';
                $where['jd.space_ids'] = $spa;
            }
            $list = model('\app\admin\model\jy\Design')
                ->alias('jd')
                ->where($where)
                ->where('is_del = 0')
                ->order('weigh desc')
                ->paginate($pageSize, false, ['page' => $pageIndex]);
            if ($list) {
                foreach ($list as &$design) {
                    // 是否点赞
                    if ($this->auth) {
                        $praise = model('\app\admin\model\jy\DesignPraise')->where(['user_id' => $this->auth->id, 'design_id' => $design['id']])->find();
                        if ($praise) {
                            $design['isPraise'] = 1;
                        } else {
                            $design['isPraise'] = 0;
                        }
                    } else {
                        $design['isPraise'] = 0;
                    }
                    $design['cover_images'] = cdnurl($design['cover_images']);
                    $productList = model('\app\admin\model\jy\DesignProduct')->alias('jdp')
                        ->join('jy_product jp', 'jp.id = jdp.product_id', 'LEFT')
                        ->where(['jdp.design_id' => $design['id'], 'jp.is_del' => 0, 'jp.status' => ['neq', '0']])->select();
                    $dProList = [];
                    if ($productList) {
                        foreach ($productList as $product) {
                            $dProList[] = $product['product_name'];
                        }
                    }
                    $design['productList'] = $dProList;
                }
            }
            $result = array("total" => $list->total(), "rows" => $list->items());
            $this->success('', $result);
        }
    }

    public function getDesignById($designId = NULL)
    {
        if (!$designId) {
            $this->error(__('Parameter %s can not be empty', 'designId'));
        }
        $design = model('\app\admin\model\jy\Design')->where('id', $designId)->find();
        if (!$design) {
            $this->error(__('No Results were found'));
        }
        // 是否点赞
        if ($this->auth) {
            $praise = model('\app\admin\model\jy\DesignPraise')->where(['user_id' => $this->auth->id, 'design_id' => $design['id']])->find();
            if ($praise) {
                $design['isPraise'] = 1;
            } else {
                $design['isPraise'] = 0;
            }
        } else {
            $design['isPraise'] = 0;
        }
        // 查询产品配置
        $designProList = model('\app\admin\model\jy\DesignProduct')->where(['design_id' => $design['id'], 'is_del' => 0])->select();
        $productList = [];
        if ($designProList) {
            foreach ($designProList as $item) {
                $product = model('\app\admin\model\jy\Product')->where(['id' => $item['product_id'], 'is_del' => 0])->find();
                if (!$product) {
                    continue;
                }
                $product['cover_images'] = cdnurl($product['cover_images']);
                $productList[] = $product;
            }
        }
        $design['productList'] = $productList;
        $design['cover_images'] = cdnurl($design['cover_images']);
        // 查询案例图
        $designImageList = model('\app\admin\model\jy\DesignImage')->where(['design_id' => $design['id'], 'is_del' => 0])->select();
        if ($designImageList) {
            foreach ($designImageList as &$images) {
                $itemImages = explode(',', $images['item_images']);
                $itemImageList = [];
                if ($itemImages) {
                    foreach ($itemImages as &$image) {
                        $image = cdnurl($image);
                        $itemImageList[] = $image;
                    }
                }
                $images['itemImageList'] = $itemImageList;
            }
            $design['designImageList'] = $designImageList;
        }
        self::addDesignScanById($designId);
        $this->success('', $design);
    }

    public function getDesignSearchCondition()
    {
        $layout = model('\app\common\model\Config')->where('name', 'layout_list')->find();
        $layouts = [];
        if ($layout) {
            $layouts = get_object_vars(json_decode($layout['value']));
        }
        $style = model('\app\common\model\Config')->where('name', 'style_list')->find();
        $styles = [];
        if ($style) {
            $styles = get_object_vars(json_decode($style['value']));
        }
        $space = model('\app\common\model\Config')->where('name', 'space_list')->find();
        $spaces = [];
        if ($space) {
            $spaces = get_object_vars(json_decode($space['value']));
        }
        $result = [
            'layoutList' => $this->condition2Obj($layouts),
            'styleList'  => $this->condition2Obj($styles),
            'spaceList'  => $this->condition2Obj($spaces),
        ];
        $this->success('', $result);
    }

    /**
     * 搜索数组转为对象
     */
    private function condition2Obj($list)
    {
        $newList = [];
        foreach ($list as $k => $l) {
            $newList[] = ['id' => $k, 'name' => $l];
        }
        return $newList;
    }

    private function addDesignScanById($designId = NULL)
    {
        if (!$this->auth->isLogin()) {
            return false;
        }
        if (!$designId) {
            $this->error(__('Parameter %s can not be empty', 'designId'));
        }
        $design = model('\app\admin\model\jy\Design')->where('id', $designId)->find();
        if (!$design) {
            $this->error(__('No Results were found'));
        }
        $userId = $this->auth->id;
        $today = date("Y-m-d", time());
        $row = model('\app\admin\model\jy\DesignScan')->where(['design_id' => $designId, 'user_id' => $userId, 'create_time' => ['>=', $today]])->find();
        if ($row) {
            $row['update_time'] = date("Y-m-d H:i:s", time());
            $row->isUpdate(true)->save();
        }
        Db::startTrans();
        try {
            $row = model('\app\admin\model\jy\DesignScan')->where(['design_id' => $designId, 'user_id' => $userId])->find();
            if (!$row) {
                model('\app\admin\model\jy\DesignScan')->insert(['design_id' => $designId, 'user_id' => $userId]);
                $design->scan_user_count++;
            }
            $design->scan_count++;
            $design->update_time = date("Y-m-d H:i:s", time());
            $design->isUpdate(true)->save();
            Db::commit();
        } catch (ValidateException | PDOException | Exception $e) {
            Db::rollback();
            return false;
        }
        return true;
    }
}
